<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
require_once ('Entity/Doc_Categories_Entity.php');
class Doc_Categories_Model extends Doc_Categories_Entity
{
    public function __construct()
    {
        parent::__construct();
    }

    public function getMenuByAlias($alias)
    {
        $sql = "SELECT id FROM doc_categories WHERE alias = ?"; 
        $query = $this->db->query($sql, array($alias));
        $obj = $query->row();
        if ($obj) {
            return $obj->id;
        }
        return 0;
    }
    
    public function categoryList()
    {
        $sql = "SELECT m.id, m.title, m.alias, c.title as ctitle, c.alias as calias, c.id as cid, 
                m.order, c.`order` as corder, count(*) as download
            FROM doc_menus m
            INNER JOIN doc_categories c ON c.mid = m.id
            INNER JOIN doc_documents d ON d.cid = c.id
            WHERE m.status = 1 AND c.status = 1
            GROUP BY c.id
            ORDER BY m.order ASC, c.order ASC";
        $query = $this->db->query($sql);
        return $query->result();
    }

     public function dataSort($field, $order)
    {
      $xOrder =  $order == 'asc' ? 'desc' : 'asc';
      $img = $order == 'desc' ? '<img src=\'/data/admin/down.jpg\' />' : ' <img src=\'/data/admin/up.jpg\' />';  
      $url = anchor('doc_categories/sort/'.$field.'/'.$xOrder, t($field).$img);
      $_SESSION['sm_sort_doc_categories'] = array('field' => $field, 'order' => $order, 'url' => $url);
    }
    
    public function dataIndex($target)
    {
        $numshow = 25;
        $this->db->select('doc_categories.id, doc_categories.title, doc_categories.created, doc_categories.status, doc_categories.order, doc_menus.title as mid_type');
        $this->db->from('doc_categories');

        $this->db->join('doc_menus', 'doc_categories.mid = doc_menus.id', 'LEFT');

        if ($this->session->userdata('sm_filter_doc_menus'))
            $this->db->where('doc_categories.mid', $this->session->userdata('sm_filter_doc_menus'));
        if ($this->session->userdata('sm_find_doc_categories')) {
            $this->db->like('doc_categories.title', $this->session->userdata('sm_find_doc_categories'));
        }
        if (isset($_SESSION['sm_sort_doc_categories'])) {
            $sort = $_SESSION['sm_sort_doc_categories'];
            $this->db->order_by('doc_categories.' . $sort['field'], $sort['order']);
        } else {
            $this->db->order_by('doc_categories.created', 'desc');
        }
        $this->db->limit($numshow, $target);
        $query = $this->db->get();
        $paging = paging_admin('doc_categories/index', $this->_total(), $numshow, 4);
        return array(
            'query' => $query,
            'paging' => $paging,
            'fil_doc_menus' => $this->Filter_doc_menus(),
            'formFind' => $this->formFind());
    }

    private function cbo_doc_menus($id = 0)
    {
        $this->load->helper("form");
        $query = $this->db->get("doc_menus");
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $sl = $id == 0 ? set_value("mid") : $id;
        return form_dropdown("mid", $options, $sl);
    }

    private function _total()
    {
        return $this->db->count_all_results("doc_categories");
    }

    private function _checkdoc_categoriesById($id)
    {
        $query = $this->db->get_where("doc_categories", array("id" => $id));
        if ($query->num_rows() > 0)
            return true;
        else {
            notify_set_messages(notify_atten(t("Record không tồn tại")), "doc_categories");
            return false;
        }
    }

    private function formFind()
    {
        $this->load->helper('form');
        $attributes = array('name' => 'frmFind', 'id' => 'frmFind');
        $f = form_open(site_url('doc_categories/find'), $attributes);
        $data = array(
            'name' => 'txt_find',
            'id' => 'txt_find',
            'value' => '',
            'style' => 'width:200px');
        $f .= form_input($data);
        $s = array(
            'name' => 'submit',
            'value' => t('Find'),
            'class' => 'ibutton green',
            'style' => 'margin-left:10px');
        $f .= form_submit($s);
        if ($this->session->userdata('sm_find_doc_categories')) {
            $r = array(
                'name' => 'btnReset',
                'value' => 'Reset',
                'class' => 'ibutton red',
                'style' => 'margin-left:10px');
            $f .= form_submit($r);
        }
        $f .= form_close();
        return $f;
    }

    private function Filter_doc_menus()
    {
        $this->load->helper('form');
        $query = $this->db->get('doc_menus');
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $id = !$this->session->userdata('sm_filter_doc_menus') ? 0 : $this->session->userdata('sm_filter_doc_menus');
        $attributes = array('name' => 'frmFilterdoc_menus', 'id' => 'frmFilterdoc_menus');
        $f = form_open(site_url('doc_categories/filterdoc_menus'), $attributes);
        $f .= form_dropdown('mid', $options, $id);
        $data = array(
            'name' => 'btnFilterdoc_menus',
            'class' => 'ibutton green',
            'style' => 'margin-left:10px',
            'value' => t('Filter'));
        $f .= form_submit($data);
        if ($this->session->userdata('sm_filter_doc_menus')) {
            $r = array(
                'name' => 'btnReset',
                'class' => 'ibutton red',
                'style' => 'margin-left:10px',
                'value' => 'Reset');
            $f .= form_submit($r);
        }
        $f .= form_close();
        return $f;
    }


    public function dataEdit($id)
    {
        if (!$this->_checkdoc_categoriesById($id))
            return redirect(site_url('doc_categories'));
        $query = $this->db->get_where('doc_categories', array('id' => $id));
        
        return array('query' => $query, 'cbo_doc_menus' => $this->cbo_doc_menus($query->row('mid')));
    }

    public function dataAdd()
    {
        return array('cbo_doc_menus' => $this->cbo_doc_menus());
    }

    public function checkForm()
    {
        $this->form_validation->set_rules('title', t('title'), 'trim|required');
        $this->form_validation->set_rules('summary', t('summary'), 'trim|required');
        $this->form_validation->set_rules('created', t('created'), 'trim|required');
        $this->form_validation->set_rules('status', t('status'), 'trim');
        $this->form_validation->set_rules('order', t('order'), 'trim|required|integer');
        $this->form_validation->set_rules('keyword', t('keyword'), 'trim');
        $this->form_validation->set_rules('description', t('description'), 'trim');
        $this->form_validation->set_rules('mid', t('mid'), 'trim|required|integer');
        return $this->form_validation->run();
    }

    public function doUpdate()
    {
        $this->load->helper('text');
        $title = $this->input->post('title');
        $time = strtotime($this->input->post('created'));
        
        $this->setTitle($title);
        //$this->setAlias(iurl_title($title));
        $alias = isset($_POST['alias']) ? $_POST['alias'] : iurl_title($title);
        $this->setAlias($alias);
        $this->setCreated($time);
        
        $this->setSummary($this->input->post('summary'));
       
        $this->setStatus($this->input->post('status'));
        $this->setOrder($this->input->post('order'));
        $this->setKeyword($this->input->post('keyword'));
        $this->setDescription($this->input->post('description'));
        $this->setMid($this->input->post('mid'));

        if (isset($_POST['idx'])) {
            $id = decrypt($_POST['idx']);
            $this->setId($id);
            $this->setChanged(time());
        } 
        return $this->save();
    }

    public function docMenuDel($id)
    {
        $sql = "SELECT id FROM doc_documents WHERE cid = ?"; 
        $query = $this->db->query($sql, array($id));
        $obj = $query->row();
        if ($obj) {
            return false;
        }
        $this->del($id);
        return true;
    }
    

}
